package com.qf.md.unit.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.common.PageParam;
import com.qf.common.PageVO;
import com.qf.entity.md.unit.MdUnitMeasure;
import com.qf.exception.CustomerException;
import com.qf.md.unit.dao.MdUnitMeasureDAO;
import com.qf.md.unit.param.UnitSearchParam;
import com.qf.md.unit.service.MdUnitMeasureService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Service
public class MdUnitMeasureServiceImpl implements MdUnitMeasureService {
    @Resource
    private MdUnitMeasureDAO mdUnitMeasureDAO;
    @Override
    public PageVO<MdUnitMeasure> unitPage(UnitSearchParam unitSearchParam) {
        PageHelper.startPage(unitSearchParam.getPageNum(),unitSearchParam.getPageSize());
        List<MdUnitMeasure> list = mdUnitMeasureDAO.selectPage(unitSearchParam);
        PageInfo<MdUnitMeasure> pageInfos = new PageInfo<>(list);
        if (pageInfos != null){
            //PageVO 定向将一些垃圾年数据给过滤掉了，只传给前端有用的数据
            return new PageVO<>(pageInfos.getTotal(),pageInfos.getList());
        //{"total":16, "dataList": [{},{},...]}
        }
        return null;
    }

    @Override
    public int saveMdUnitMeasure(MdUnitMeasure mdUnitMeasure) {
        if (mdUnitMeasure == null){
            throw new CustomerException("参数为空");
        }
        return mdUnitMeasureDAO.insertMdUnitMeasure(mdUnitMeasure);
    }

    @Override
    public MdUnitMeasure findById(Long id) {
        if (id == null){
            throw new CustomerException("参数为空");
        }
        if (mdUnitMeasureDAO.selectByPrimaryKey(id) == null){
            throw new CustomerException("50001","数据不存在");

        }

        return mdUnitMeasureDAO.selectByPrimaryKey(id);
    }

    @Override
    public int updateMdUnitMeasure(MdUnitMeasure mdUnitMeasure) {
        if (mdUnitMeasure == null){
            throw new CustomerException("参数为空");
        }
        if (mdUnitMeasureDAO.selectByPrimaryKey(mdUnitMeasure.getMeasureId()) == null){
            throw new CustomerException("50001","数据不存在");

        }
        return mdUnitMeasureDAO.updateMdUnitMeasure(mdUnitMeasure);
    }

    @Override
    public List<MdUnitMeasure> findByPrimaryUnit() {
        List<MdUnitMeasure> list = mdUnitMeasureDAO.selectByPrimaryUnit();

        return list;
    }

    @Override
    public int deleteMdUnitMeaeasure(Long id) {
        if (mdUnitMeasureDAO.selectByPrimaryKey(id) == null){
            throw new CustomerException("50001","数据不存在");

        }
        if (mdUnitMeasureDAO.deleteByPrimaryKey(id) > 0){
            return 1;
        }

        return 0;
    }

    @Override
    public int deleteBatch(List<Long> ids) {

        return mdUnitMeasureDAO.deleteBatch(ids);
    }

    @Override
    public void uploadExcel(MultipartFile file) {//excel数据都在file对象中
        /**
         * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
         */
      final int BATCH_COUNT = 100;
        /**
         * 缓存的数据
         *  List<MddUnitMeasure> cacheList = new ArrayList<MddUnitMeasure>(100);
         */
         List<MdUnitMeasure> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        InputStream inputStream = null;//将excel表格的对象转成一个输入流对象
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        EasyExcel.read(inputStream, MdUnitMeasure.class, new ReadListener<MdUnitMeasure>(){

            @Override
            public void invoke(MdUnitMeasure mdUnitMeasure, AnalysisContext analysisContext) {
                System.out.println("::::"+mdUnitMeasure);
                //向数据库中插入数据
                cachedDataList.add(mdUnitMeasure);
                if (cachedDataList.size() >= BATCH_COUNT) {
                    // 存储完成清理 list
                    mdUnitMeasureDAO.insertBatchMdUnitMeasure(cachedDataList);
                    cachedDataList.clear();
                }

            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                //处理剩余的数据
                if (cachedDataList.size() > 0) {
                    mdUnitMeasureDAO.insertBatchMdUnitMeasure(cachedDataList);
                }
            }
        }).sheet().doRead();
    }

    @Override
    public void downloadExcel(HttpServletResponse response) {
        //1.查询导出的数据
        List<MdUnitMeasure> list = mdUnitMeasureDAO.selectAllUnit();
        if (list == null){
            throw new CustomerException("50001","数据不存在");
        }
        //设置响应头信息
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = null;
        try {
            fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        //String fileName = "测试";
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        try {
            EasyExcel.write(response.getOutputStream(), MdUnitMeasure.class)
                    .sheet("模板")
                    .doWrite(list);
        } catch (IOException e) {
            throw new CustomerException("导出失败");
        }
    }
}
